package memberhandler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/orders"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

// GetOrderList 获取定单列表API
func GetMemberList(ctx *gin.Context) {
	// 请求参数处理
	param := &request.MemberListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	// 查询结果
	data := memberdao.NewMemberDao().GetMemberList(param)
	// 分页信息
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

// HandleChangeState 更新会员状态
func HandleChangeState(ctx *gin.Context)  {
	param := &struct {
		Id     int  `json:"id" binding:"required,gt=0"`
		State int8 `json:"state"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	Response(ctx)("", CodeUpdateSuccess, memberdao.NewMemberDao().UpdateMemberStatus(param.Id, param.State).Unwrap())(OK)
}

func HandleInsertMemberPclBalance(ctx *gin.Context)  {
	param := &struct {
		TradeNo     string  `json:"tradeNo" form:"tradeNo" binding:"required"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	orderInfo := dao.NewOrderDao().GetOrderInfoByTradeNo(param.TradeNo).Unwrap().(*orders.OrderModel)
	memberInfo := memberdao.NewMemberDao().GetMemberInfoByUuId(orderInfo.MemberId).Unwrap().(*membermodel.MembersModel)

	orderTotal := memberdao.NewMemberDao().SumMemberOrderByTradeNo(orderInfo.TradeNo).Unwrap().(int64)

	tx, key := dbs.GormBegin("UpdateXmRechargeOrderStatusDoneByTradeNo")
	// 订单退款，退款至余额
	rechargeMoneyUpdateData := memberdao.NewMemberDao().UpdateBalanceAmount(tx, &membermodel.MemberPclBalance{
		MemberId:    memberInfo.ID,
		Amount:      -int(orderTotal),
		Type:        4,
		TradeNo:     "R" + param.TradeNo,
		Description: fmt.Sprintf(`余额回滚`),
		CreateTime:  time.Now().Format("2006-01-02 15:04:05"),
		UpdateTime:  time.Now().Format("2006-01-02 15:04:05"),
	})
	if rechargeMoneyUpdateData.Err != nil {
		dbs.GormRollback(tx, key, rechargeMoneyUpdateData.Err)
	}
	dbs.GormCommit(tx, key)
}